//
//  ZSAssistantViewController.swift
//  creativeassistant
//
//  Created by 灵工邦 on 2025/2/13.
//

import UIKit
import ProgressHUD
import IQKeyboardManagerSwift

class ZSAssistantViewController: ZSBaseViewController {

    /// 0 AI智能助手 1 密友 2 树洞 3 生活百科助手 4 朋友圈参照创作 5 朋友圈文案
    var aiIdentity: Int = 0
    /// 朋友圈参照创作模版
    var wechatTimeLineTemplate: String = ""
    @IBOutlet weak var navigationHeight: NSLayoutConstraint!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var descLabel: UILabel!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var bottom: NSLayoutConstraint!
    
    lazy var data: ZSAssistantModel = {
        switch aiIdentity {
        case 1:
            if let data = ZSCloseFriendHelper.encyclopediasInfo() {
                return data
            }
            let model = ZSAssistantModel()
            let messageModel = ZSAssistantMessageModel()
            messageModel.message = "我一直在这里，随时倾听你的心声"
            messageModel.fromeType = 1
            model.datas = [messageModel]
            let status = ZSCloseFriendHelper.dc_saveCloseFriendInfo(closeFriendInfo: model)
            if status {
                
            }
            return model
        case 2:
            if let data = ZSTreeHoleHelper.treeHoleInfo() {
                return data
            }
            let model = ZSAssistantModel()
            let messageModel = ZSAssistantMessageModel()
            messageModel.message = "我一直在这里，随时倾听你的心声"
            messageModel.fromeType = 1
            model.datas = [messageModel]
            let status = ZSTreeHoleHelper.dc_saveTreeHoleInfo(treeHoleModel: model)
            if status {
                
            }
            return model
        case 3:
            if let data = ZSEncyclopediasHelper.encyclopediasInfo() {
                return data
            }
            let model = ZSAssistantModel()
            let messageModel = ZSAssistantMessageModel()
            messageModel.message = "我一直在这里，随时倾听你的心声"
            messageModel.fromeType = 1
            model.datas = [messageModel]
            let status = ZSEncyclopediasHelper.dc_saveEncyclopediasInfo(encyclopediasInfo: model)
            if status {
                
            }
            return model
        default:
            if let data = ZSAssistantHelper.assistantInfo() {
                return data
            }
            let model = ZSAssistantModel()
            let messageModel = ZSAssistantMessageModel()
            messageModel.message = "我一直在这里，随时倾听你的心声"
            messageModel.fromeType = 1
            model.datas = [messageModel]
            let status = ZSAssistantHelper.dc_saveAssistantInfo(assistantModel: model)
            if status {
                
            }
            return model
        }
    }()
    
    lazy var datas: Array<ZSAssistantMessageModel> = {
        return data.datas
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor(hexString: "#F0F3FD")
        navigationHeight.constant = UIApplication.shared.statusBarFrame.size.height + 44
        switch aiIdentity {
        case 1:
            titleLabel.text = "密友"
            descLabel.text = "Hi！我是你的密友"
        case 2:
            titleLabel.text = "树洞烦恼"
            descLabel.text = "Hi！我是你的树洞"
        case 3:
            titleLabel.text = "生活百科助手"
            descLabel.text = "Hi！我是你的生活百科助手"
        default:
            titleLabel.text = "AI智能助手"
            descLabel.text = "Hi！我是你的AI智能助手"
        }
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.separatorStyle = .none
        self.tableView.register(UINib(nibName: "ZSLeftMessageCell", bundle: nil), forCellReuseIdentifier: "ZSLeftMessageCell")
        self.tableView.register(UINib(nibName: "ZSRightMessageCell", bundle: nil), forCellReuseIdentifier: "ZSRightMessageCell")
        self.tableView.estimatedRowHeight = UITableView.automaticDimension
        self.tableView.rowHeight = UITableView.automaticDimension
        self.tableView.sectionHeaderHeight = CGFloat.zero
        self.tableView.sectionFooterHeight = CGFloat.zero
        if #available(iOS 15.0, *) {
            self.tableView.sectionHeaderTopPadding = 0.0
        }
        if aiIdentity == 4 {
            let messageModel = ZSAssistantMessageModel()
            messageModel.message = wechatTimeLineTemplate
            messageModel.fromeType = 2
            data.datas.append(messageModel)
            datas = data.datas
            ZSAssistantHelper.dc_saveAssistantInfo(assistantModel: data)
            self.tableView.reloadData()
            self.scrollTableViewToBottom()
            sendMessageData(text: messageModel.message)
        }
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enable = false
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.enable = true
    }
    
    @objc func keyboardWillShow(notification: Notification) {
        if let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect {
            let keyboardHeight = keyboardFrame.height
            print("键盘即将显示，高度为: \(keyboardHeight)")
            self.bottom.constant = keyboardHeight
        }
    }

    @objc func keyboardWillHide(notification: Notification) {
        if let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect {
            let keyboardHeight = keyboardFrame.height
            print("键盘即将隐藏，高度为: \(keyboardHeight)")
            self.bottom.constant = 0
        }
    }
    
    private func scrollTableViewToBottom() {
        guard datas.count > 0 else { return }
        let lastSectionIndex = tableView.numberOfSections - 1
        let lastRowIndex = tableView.numberOfRows(inSection: lastSectionIndex) - 1
        let indexPath = IndexPath(row: lastRowIndex, section: lastSectionIndex)
        tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
    }
    
    @IBAction func goBack(_ sender: UIButton) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @IBAction func sendMessage(_ sender: UIButton) {
        guard var text = textField.text, !text.isEmpty else {
            self.view.makeToast("请输入要发送的消息", position: .center)
            return
        }
        if aiIdentity == 5 {
            text = "帮我写一个朋友圈文案，主题如下【\(text)】"
        }
        let messageModel = ZSAssistantMessageModel()
        messageModel.message = text
        messageModel.fromeType = 2
        data.datas.append(messageModel)
        datas = data.datas
        self.view.endEditing(true)
        switch aiIdentity {
        case 1:
            ZSCloseFriendHelper.dc_saveCloseFriendInfo(closeFriendInfo: data)
        case 2:
             ZSTreeHoleHelper.dc_saveTreeHoleInfo(treeHoleModel: data)
        case 3:
            ZSEncyclopediasHelper.dc_saveEncyclopediasInfo(encyclopediasInfo: data)
        default:
            ZSAssistantHelper.dc_saveAssistantInfo(assistantModel: data)
        }
        self.tableView.reloadData()
        self.scrollTableViewToBottom()
        sendMessageData(text: text)
    }
    
    fileprivate func sendMessageData(text: String) {
        ProgressHUD.show()
        let urlString = baseUrl + "/lbbmajiabao/api/wenxinyiyan/chat"
        guard let url = URL(string: urlString) else {
            print("Invalid URL")
            return
        }
        let parameters: [String: Any] = [
            "messages": [
                [
                    "role": "user",
                    "content": text
                ]
            ]
        ]
        let jsonData = try? JSONSerialization.data(withJSONObject: parameters)
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = jsonData
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            ProgressHUD.dismiss()
            DispatchQueue.main.async {
                self.textField.text = ""
            }
            if let error = error {
                print("Error: \(error)")
                return
            }
            guard let data = data else {
                print("No data received")
                return
            }
            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
                   let dict = json["data"] as? [String: Any], let result = dict["result"] as? String, !result.isEmpty {
                    DispatchQueue.main.async {
                        let messageModel = ZSAssistantMessageModel()
                        messageModel.message = result
                        messageModel.fromeType = 1
                        self.data.datas.append(messageModel)
                        self.datas = self.data.datas
                        switch self.aiIdentity {
                        case 1:
                            ZSCloseFriendHelper.dc_saveCloseFriendInfo(closeFriendInfo: self.data)
                        case 2:
                             ZSTreeHoleHelper.dc_saveTreeHoleInfo(treeHoleModel: self.data)
                        case 3:
                            ZSEncyclopediasHelper.dc_saveEncyclopediasInfo(encyclopediasInfo: self.data)
                        default:
                            ZSAssistantHelper.dc_saveAssistantInfo(assistantModel: self.data)
                        }
                        self.tableView.reloadData()
                        self.scrollTableViewToBottom()
                    }
                }
            } catch {
                print("Error parsing JSON: \(error)")
            }
        }
        task.resume()
    }
    
}

extension ZSAssistantViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.datas.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = self.datas[indexPath.row]
        if model.fromeType == 1 {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "ZSLeftMessageCell", for: indexPath) as? ZSLeftMessageCell else {
                fatalError("Unable to dequeue cell")
            }
            cell.selectionStyle = .none
            cell.model = self.datas[indexPath.row]
            return cell
        }
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "ZSRightMessageCell", for: indexPath) as? ZSRightMessageCell else {
            fatalError("Unable to dequeue cell")
        }
        cell.selectionStyle = .none
        cell.model = self.datas[indexPath.row]
        return cell
       
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.datas[indexPath.row]
        if model.fromeType == 1 {
            model.isSelect = !model.isSelect
            tableView.reloadData()
        }
    }
    
}

